﻿#region Usings

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Surface.Presentation.Controls;
using System.Text.RegularExpressions;

#endregion

namespace ScrumTable.UI.View.WinTouch.CustomControl
{
    /// <summary>
    /// Validates and shows if the string is not valid. But it does not preventing from writing the text back to the binding source
    /// </summary>
    public class ValidateTextBox : SurfaceTextBox
    {

        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------
        private Thickness _oldThickness = new Thickness(0);
        private Brush _oldBorderBrush;
        #endregion 

        public string ValidateRegex { get; set; }
        public bool ValidateFileName { get; set; }

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------
     
        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------
        public ValidateTextBox()
        {
        }

        #endregion 

        #region Methods


        public bool Validate()
        {
            if (_oldBorderBrush == null) { _oldBorderBrush = BorderBrush; _oldThickness = BorderThickness; }

            if (DataContext == null || GetValidationRuleResults())
            {
                BorderBrush = _oldBorderBrush ?? BorderBrush;
                BorderThickness = _oldThickness;
                return true;
            }
            else
            {
                BorderBrush = Brushes.Red;
                BorderThickness = new Thickness(2);
                return false;
            }
        }

        private bool GetValidationRuleResults()
        {
            return ValidateAsRegex() && ValidateAsFileName();
        }

        private bool ValidateAsRegex()
        {
            return string.IsNullOrEmpty(ValidateRegex) || new Regex(ValidateRegex, RegexOptions.Compiled).IsMatch(Text);
        }

        private bool ValidateAsFileName()
        {
            return !ValidateFileName || !Path.GetInvalidFileNameChars().Any(Text.Contains);
        }

        #endregion
        #region Events

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            Validate();
            base.OnLostFocus(e);
        }

        #endregion
    }
}
